package hle.mj.circle;

public class CirCleDeQueue<E> {
	private int front;
	private int size;
	private E[] elements;
		
	private static final int DEFAULT_CAPACITY = 5;

	public CirCleDeQueue() {
		elements = (E[]) new Object[DEFAULT_CAPACITY];
	}

	public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }
    
    public void clear() {
    	for (int i = 0; i < size; i++) {
			elements[index(i)] = null;
		}
	    size = 0;
        front = 0;
    }

    public void enQueueRear(E element) {
    	ensureCapacity(size + 1);
    	elements[index(size)] = element;
    	size ++;
    }
    
    public void enQueueFront(E element) {
		ensureCapacity(size + 1);
		front = index(-1);
		elements[front] = element;
		size ++;
	}

    public E deQueueFront() {
    	E frontElement = elements[front];
    	elements[front] = null;
    	front = index(1);
    	size--;
        return frontElement;
    }

    public E front() {
        return elements[front];
    }
    
    public E real() {
    	int realIndex = index(size - 1);
		return elements[realIndex];
	}
    
    private void ensureCapacity(int capacity) {
    	int oldCapacity = elements.length;
    	if (oldCapacity >= capacity) return; 
    	int newCapacity = oldCapacity + (oldCapacity >> 1);
    	E[] newElements = (E[]) new Object[newCapacity];
    	for (int i = 0; i < oldCapacity; i++) {
    		newElements[i] = elements[index(i)];
		}
    	elements = newElements;
    	front = 0;
	}
    
    private int index(int index) {
    	index += front;
		if (index < 0) {
			return index + elements.length;
		}
		return index % elements.length;
	}
    
    @Override
    public String toString() {
    	StringBuffer buffer = new StringBuffer();
    	buffer.append("capcacity=").append(elements.length).append(",");
    	buffer.append("size=").append(size).append(",");
    	buffer.append("front=").append(front).append(",").append("[");
    	for (int i = 0; i < elements.length; i++) {
    		if (i != 0) {
				buffer.append(",");
			}
    		buffer.append(elements[i]);
		}
    	buffer.append("]");
    	return buffer.toString();
    }
}
